package action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import form.ActionForm;

import util.XmlBean;

public class ActionServlet extends HttpServlet{
	
	private static final long serialVersionUID = -3441228413680593403L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException{
		System.out.println(request.getParameter("name"));
		String path = this.getPath(request.getServletPath());
		Map<String,XmlBean> actionsMap = (Map<String, XmlBean>) this.getServletContext().getAttribute("actionsMap");
		XmlBean actionMap = actionsMap.get(path);
		String formType = actionMap.getFormType();
		ActionForm form = FullForm.full(formType, request);
		Action action = null;
		String url = "";
		try {
			Class clazz = Class.forName(actionMap.getActionType());
			action = (Action) clazz.newInstance();
			url = action.execute(request, form, actionMap.getActionForwards());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException{
		this.doGet(request, response);
	}
	
	public String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
	
}
